﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using UserLicense.Applicationes.Command;
using UserModels;
using UserRepositorys.Intface;

namespace UserLicense.Applicationes.CommandHandler
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, string>
    {
        private readonly IUserRepository _userRepository;
        private readonly IConfiguration configuration;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository"></param>
        public UserLoginCommandHandler(IUserRepository userRepository, IConfiguration configuration)
        {
            _userRepository = userRepository;
            this.configuration = configuration;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<string> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            var result = await _userRepository.GetUserInfoById(request.UserAccount, request.UserPass);

            if (result != null)
            {
                //生成JWT
                //Handler，选择签名算法
                var srithm = SecurityAlgorithms.HmacSha256;
                //Payload，存放用户信息，下面我们放了一个用户id
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub,result.UserId.ToString()),
                    new Claim(JwtRegisteredClaimNames.Name,result.UserName),
                };

                //signature
                //去除私钥并以utf8棉麻字节输出
                var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
                //使用非对称算法对私钥进行加密
                var signingKey = new SymmetricSecurityKey(secretByte);
                //使用HmacSha256来验证加密后的私钥生成数字签名
                var signingCredentials = new SigningCredentials(signingKey, srithm);
                //生成Token
                var Token = new JwtSecurityToken(
                    issuer: configuration["Authentication:Issuer"],//发布者
                    audience: configuration["Authentication:Audience"],//接收者
                    claims: claims,//存放的用户信息
                    notBefore: DateTime.UtcNow,//发布时间
                    expires: DateTime.UtcNow.AddDays(1),//有效期设置1天
                    signingCredentials//数字签名
                    );
                //生成字符串token
                var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
                return TokenStr;
            };
            return "";
        }
    }
}
